package com.tencent.sr.iris.activity.dependency;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.tencent.sr.iris.activity.common.config.DependencyConfig;
import com.tencent.sr.iris.activity.common.enums.IrisErrorCode;
import com.tencent.sr.iris.basic.service.interfaces.client.ActivityMessageClient;
import com.tencent.sr.iris.basic.service.interfaces.request.ActivityQuerySubscribeRequest;
import com.tencent.sr.iris.basic.service.interfaces.response.ActivityQuerySubscribeResponse;
import com.tencent.sr.rmall.common.exception.retail.TRetailBizException;
import com.tencent.sr.rmall.common.primitive.HttpResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

@Component
@Slf4j
public class ActivityMessageDependency {

    @Resource
    private ActivityMessageClient activityMessageClient;

    @Resource
    private DependencyConfig dependencyConfig;

    /**
     * 查询订阅信息
     *
     * @return
     */
    public List<ActivityQuerySubscribeResponse> querySubscribe(ActivityQuerySubscribeRequest request) {
        Integer batchSize = Optional.ofNullable(dependencyConfig.getConfigs().get("querySubscribe"))
                .map(DependencyConfig.Config::getBatchSize).orElse(20);

        List<String> activityIdList = request.getActivityIdList();
        List<ActivityQuerySubscribeResponse> responseList = Lists.newArrayListWithCapacity(activityIdList.size());
        List<List<String>> lists = Lists.partition(activityIdList, batchSize);
        for (List<String> idList : lists) {
            request.setActivityIdList(idList);
            HttpResult<List<ActivityQuerySubscribeResponse>> result = activityMessageClient.querySubscribe(request);
            if (result == null || !result.isSuccess()) {
                log.error("请求activityMessageClient.querySubscribe失败：req：{}，resp：{}", JSON.toJSONString(request),
                        JSON.toJSONString(result));
                throw new TRetailBizException(IrisErrorCode.QUERY_SUBSCRIBE_INFO_FAIL);
            }
            responseList.addAll(result.getData());
        }
        return responseList;
    }
}
